<?php
/**
 * $upload = new Upload(['name'=> 'name', 'type' => ['image/jpeg', 'text/csv', 'text/plain']]);
 * $res = $upload->upload();
 */
namespace app\tools;

class Upload
{
	private $path = './public/uploads/';
	private $prefix = 'tn_';
	private $type = [
		'image/jpeg',
		'image/png',
		'image/gif',
		'text/csv',
		'text/plain'
	];
	private $size = 247786;
	private $name = '';
	// 是否远程服务器 true：是 false：否
	private $remote = false;
	public function __construct(Array $param = [])
	{
		if (!empty($param)) {
			$attr = get_object_vars($this);
			foreach ($attr as $key => $value) {
				if (key_exists($key, $param) && !empty($param[$key])) {
					$this->$key = $param[$key];
				}
			}
		}
	}

	/**
	 * 数字随机串
	 *
	 * @return void
	 * @author sunhaoqiang(shqdev@163.com)
	 * @time 2019-12-25 14:53
	 */
	private function getRandName()
	{
		$order_id_main = date('YmdHis') . rand(10000000, 99999999);
		$order_id_len = strlen($order_id_main);
		$order_id_sum = 0;
		for ($i = 0; $i < $order_id_len; $i++) {
			$order_id_sum += (int)(substr($order_id_main, $i, 1));
		}
		$osn = 'YN' . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

		return $osn; //201807041332258742313727
	}

	/**
	 * 防止文件重复、首先生成一个唯一的随机数作为文件的名字
	 *
	 * @param String $file_name
	 * @return String
	 * @author sunhaoqiang(shqdev@163.com)
	 * @time 2019-12-25 15:07
	 */
	private function getNewFileName(String $file_name) : String
	{
		$mark = 'normal';
		if (stristr($file_name, 'alipay')) {
			$mark = 'alipay';
		}

		if (stristr($file_name, '微信支付')) {
			$mark = 'wechat';
		}

		$ext = pathinfo($file_name, PATHINFO_EXTENSION);
		return uniqid($mark . '_' . $this->prefix . date('YmdHis') . '_', true) . '.' . $ext;
	}

	private function mkdir()
	{
		//按照日期创建子目录
		$sub_path = date('Ymd').'/';
		//创建目录，先判断 uploads 是否存在，不存在则创建该目录
		if(!is_dir($this->path . $sub_path)){
			mkdir($this->path . $sub_path,0777,true);
		}

		return $this->path . $sub_path;
	}

	/**
	 * 上传文件类型验证
	 *
	 * @param Array $file
	 * @return Bool
	 * @author sunhaoqiang(shqdev@163.com)
	 * @time 2019-12-25 15:41
	 */
	private function validate(Array $file) : Bool
	{
		$type = $file['type'];
		if(!in_array($type, $this->type)){
			throw new \Exception("请上传正确文件类型：" . implode(',', $this->type));
		}

		$finfo = new \finfo(FILEINFO_MIME_TYPE);
		$type = $finfo->file($file['tmp_name']);
		if(!in_array($type, $this->type)){
			throw new \Exception("请上传正确文件类型：" . implode(',', $this->type));
		}

		// 验证文件大小
		return true;
	}

	private function move(Array $file, String $to)
	{
		$res = $this->validate($file);
		if ($res) {
			if(move_uploaded_file($file['tmp_name'], $to)){
				return $to;
			}else{
				return false;
			}
		}
	}

	public function upload(){
		$files = $_FILES;
		$data = [];
		if (empty($this->name)) {
			foreach ($files as $key => $value) {
				$filename = $this->getNewFileName($value['name']);
				$filename = $this->mkdir().$filename;
				if ($this->move($value, $filename)) {
					$data[$key] = $filename;
				}

			}

		} else {
			if (isset($files[$this->name])) {
				$filename = $this->getNewFileName($files[$this->name]['name']);
				$filename = $this->mkdir() . $filename;
				if ($this->move($files[$this->name], $filename)) {
					return $filename;
				}
			}
		}
		
		return empty($data) ? false : $data;
	}
}